import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from '../css/buypay.module.css';
import leftImg from '../assets/left.png';
import hourseImg from '../assets/hourse3.png';
import { createOrder } from '../api/buypay'; 

const PayPage = () => {
    const navigate = useNavigate();
    const [shopData, setShopData] = useState(null);
    const [deata, setDeata] = useState(null);
    const [allPrice, setAllPrice] = useState('');
    const [userid, setUserid] = useState('');
    const [address, setAddress] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    useEffect(() => {
        // 从sessionStorage获取数据
        const shopData = JSON.parse(sessionStorage.getItem("shopData"));
        const deata = JSON.parse(sessionStorage.getItem("reservedTicket"));
        const allPrice = sessionStorage.getItem("allPrice");
        const userid = sessionStorage.getItem("userid");
        const address = sessionStorage.getItem("address");

        setShopData(shopData);
        setDeata(deata);
        setAllPrice(allPrice);
        setUserid(userid);
        setAddress(address);
    }, []);

    // 处理订单状态更新
    const handleOrderStatus = async (status) => {
        try {
            setLoading(true);
            const updatedShopData = { ...shopData, status };
            
            const response = await createOrder(updatedShopData, userid);
            console.log(response.data);
            
            if (response.data.code === 1) {
                return true;
            }
            return false;
        } catch (error) {
            console.error('Error:', error);
            setError(error.message);
            return false;
        } finally {
            setLoading(false);
        }
    };

    // 返回上一页（取消订单）
    const handleBack = async () => {
        const success = await handleOrderStatus(2); // 改变商品已取消的状态值为2
        if (success) {
            navigate('/suborder');
        }
    };

    // 跳转首页
    const handleHome = () => {
        navigate('/home');
    };

    // 点击立即支付
    const handlePayment = async () => {
        const success = await handleOrderStatus(4); // 改变已支付的状态值为4
        if (success) {
            navigate('/successpay');
        }
    };

    if (!deata || !shopData) {
        return <div className={styles.loading}>加载中...</div>;
    }

    if (loading) {
        return <div className={styles.loading}>处理中...</div>;
    }

    if (error) {
        return <div className={styles.error}>错误: {error}</div>;
    }

    return (
        <div className={styles.payContainer}>
            <div className={styles.top}>
                <div className={styles.topContainer}>
                    <div className={styles.left}>
                        <img src={leftImg} alt="返回" onClick={handleBack} />
                        <div className={styles.line}></div>
                        <img className={styles.homeIcon} src={hourseImg} alt="首页" onClick={handleHome} />
                    </div>
                </div>
                <p className={styles.title}>支付</p>
            </div>

            <div className={styles.money}>
                <b className={styles.name}>{deata.name}</b>
                <h2 className={styles.orderPrice}>￥{allPrice}元</h2>
            </div>

            <div className={styles.pay}>
                <span className={styles.pay}>收款方</span>
                <p className={styles.address}>{address}</p>
            </div>

            <button className={styles.payment} onClick={handlePayment} disabled={loading}>
                {loading ? '处理中...' : '立即支付'}
            </button>

            <div className={styles.company}>
                <span>支付安全由中国人民财产保险股份有限公司承包</span>
            </div>
        </div>
    );
};

export default PayPage;